<?php
class Post extends AModel
{
	private $author = false;
	private $num_comments = false;

    public function __construct($in_args=array())
	{
		// This type of object is revision lockable
		$this->table = 'posts';

		$this->verifyArguments($in_args);

		$this->import($in_args);
	}

	public function getFormattedTitle()
	{
		return $this->get('title');
	}

	public function getFormattedBody()
	{
		$no_windows_newlines = str_replace("\r", "", $this->get('body'));
		$html_newlines = str_replace("\n", "</p><p>\r\n", $no_windows_newlines);
		return "<p>" . $html_newlines . "</p>\n";
	}

	public function getAuthor()
	{
		if(!$this->author)
		{
			$this->author = UserMapper::get()->find($this->get('author'));
		}

		return $this->author;
	}

	public function getNumComments()
	{
		if($this->num_comments == false)
		{
			$this->num_comments = CommentMapper::get()->findNumByPost($this);
		}
		return $this->num_comments;
	}

	public function setAuthor($user)
	{
		$this->author = $user;
		$this->set('author', $user->getId());
	}

	private function verifyArguments(&$in_args)
	{
		$errors = false;

		if ($errors)
			$this->invalidArguments(__CLASS__);
	}
	
	public function asRSS()
	{
		$fields = array(
			'title' => '<![CDATA[' . $this->get('title') . ']]>',
			'link' => "http://" . $_SERVER['SERVER_NAME'] . "/blog/post/" . $this->getId(),
			'description' =>  '<![CDATA[' . substr(strip_tags($this->get('body')),0,100) . '[...]' . ']]>',
			'content:encoded' => '<![CDATA[' . $this->getFormattedBody() . ']]>',
			'pubDate' => date('r', $this->get('date_added'))
		);

		return $this->asXML($fields, true);
	}
}
?>